package org.rcy.framework.security.stateless;

import org.rcy.framework.security.authentication.AuthenticationToken;
import org.rcy.framework.security.login.LoginSuccessAdvice;
import org.rcy.framework.security.login.NullLoginSuccessAdvice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 吴康桥
 * @Description
 * @date 2022/10/31 17:01
 */


public abstract class StatelessLoginSuccessHandler implements AuthenticationSuccessHandler {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired(required = false)
	protected LoginSuccessAdvice loginSuccessAdvice = new NullLoginSuccessAdvice();

	@Override
	public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
		try {
			AuthenticationToken authenticationToken = (AuthenticationToken) authentication;
			loginSuccessAdvice.beforeHandle(httpServletRequest,httpServletResponse,authenticationToken);
			this.successHandle(httpServletRequest,httpServletResponse,authenticationToken);
			loginSuccessAdvice.afterHandle(httpServletRequest,httpServletResponse,authenticationToken);
		}catch (Exception e){
			this.logger.error(e.getMessage(),e);
		}
	}

	protected abstract void successHandle(HttpServletRequest request, HttpServletResponse response, AuthenticationToken authentication) throws Exception;

	public void setLoginSuccessAdvice(LoginSuccessAdvice loginSuccessAdvice) {
		this.loginSuccessAdvice = loginSuccessAdvice;
	}
}
